import { Injectable } from '@nestjs/common';
import { UserService } from '../user/user.service';
import * as bcrypt from 'bcrypt';
import { JwtService } from '@nestjs/jwt';

@Injectable()
export class AuthService {
  constructor(
    private readonly userService: UserService,
    private jwtService: JwtService,
  ) {}

  async validateUser(username: string, password: string): Promise<any> {
    const user = await this.userService.findOneByUsername(username);
    console.log('====login====', user.password);
    if (user && bcrypt.compareSync(password, user.password)) {
      return user;
    }
    console.log('first login');
    return null;
  }
  createToken(user) {
    const token = this.jwtService.sign({
      username: user.username,
      id: user.id,
    });
    return { token };
  }
}
